#!python
# -*- coding: utf-8 -*-

# Author: mingy
# Only for learning and communication purposes, prohibited for illegal use
# 仅用于学习交流，禁止用于非法用途

import os
import sys

RESET="\033[0m"
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"

# 读取文件
def read_file(file_path):
    with open(file_path, 'rb') as file:
        return file.read()

# 写入文件
def write_file(file_path, data):
    with open(file_path, 'wb') as file:
        file.write(data)

# 搜索替换
def search_and_replace(data, search_bytes, replace_bytes):
    search_len = len(search_bytes)
    replace_len = len(replace_bytes)
    offset = 0
    while True:
        offset = data.find(search_bytes, offset)
        if offset == -1:
            break
        # 确保替换不会与下一个搜索重叠（简单安全检查）
        if offset + replace_len > len(data):
            raise ValueError(f"{RED}[-] 替换会与文件末尾重叠{RESET}")
        # 执行替换
        data = data[:offset] + replace_bytes + data[offset + search_len:]
        # 移动偏移量以继续搜索
        offset += replace_len
    return data

def main(file_path, search_hex, replace_hex):
    # 将十六进制字符串转换为字节数组
    search_bytes = bytes.fromhex(search_hex)
    replace_bytes = bytes.fromhex(replace_hex)

    if not os.path.isfile(file_path):
        print(f"{RED}[-] 错误: 文件 '{file_path}' 不存在{RESET}")
        return

    # 读取PE文件
    pe_data = read_file(file_path)

    # 执行搜索和替换
    modified_data = search_and_replace(pe_data, search_bytes, replace_bytes)
      
    # 将修改后的数据写回文件
    write_file(file_path, modified_data)
    print(f"{BLUE}[+] 成功: 文件修改成功{RESET}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(f"{RED}[-] 错误: 请提供文件路径或文件名作为参数{RESET}")
        print(f"{YELLOW}[!] 使用方法: python {sys.argv[0]} <xray文件路径或文件名>{RESET}")
        sys.exit(1)
    file_path = sys.argv[1]
    
    search_hex = "434F4D4D554E495459"
    replace_hex = "414F4D4D554E495459"

    if len(search_hex) != len(replace_hex):
        print("{YELLOW}[!] 警告：替换十六进制字符串的长度与搜索十六进制字符串不同{RESET}")
        sys.exit(1)

    main(file_path, search_hex, replace_hex)